from prg.common.import_file import *
from prg.common.object_message import MessageBase
from prg.command_info import CommandInfo
from prg.header_info import HeaderInfo
from prg.common.common_base import CommonBase
from prg.bll.config_bll import ConfigBll
import socket


class RunControl(MessageBase):
    def __init__(self, control=None):
        super().__init__(name="run_control")
        cfg = ConfigBll.instance().get_base_config()
        self.ip = cfg.control.ip
        self.port = cfg.control.port
        self.password = cfg.control.password
        self.control = control

    def entry(self):
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind((self.ip, self.port))
        server_socket.listen(5)
        while self.is_run():
            control_item, control_addr = server_socket.accept()
            with control_item as control_socket:
                try:
                    header_inf = HeaderInfo(client_socket=control_socket)
                    en = header_inf.get_head_entity(key=self.password)
                    if self.control is not None:
                        self.control(en)
                except Exception as e:
                    print("control error: %s" % e)

    def send(self, name, cmd, arg):
        arg_val = CommonBase.aes_encryption_json(key=self.password, entity=arg)
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.connect((self.ip, self.port))
        with server_socket as socket_item:
            cmd = CommandInfo(name=name, command=cmd, arg=arg_val, socket_item=socket_item)
            cmd.send()



